//
//  AppDelegate.m
//  ShangHaiHuDongApp
//
//  Created by 刘应平 on 2017/6/13.
//  Copyright © 2017年 刘应平. All rights reserved.
//

#import "AppDelegate.h"
#import <AlipaySDK/AlipaySDK.h>
#import "Reachability.h"
#import "ZJTabBarController.h"
#import "LoginViewController.h"
#import <UMSocialCore/UMSocialCore.h>
#import "ZJPushInfoManager.h"
#import "PolyvSettings.h"
#import "PolyvUtil.h"
#import "LoginViewController.h"
#import "LPActivityDetailViewController.h"
#import "VHallApi.h"
#import "ZJReportViewController.h"
#import "ZJLoginJudgeManager.h"
#import "CManager.h"
#import "ZJShareClaimViewController.h"
#import "GTResouseDetailViewController.h"
#import "ShareResouceDetailViewController.h"
#import "ZJNavigationController.h"
#import <AFNetworking.h>
#import "ZJWebViewController.h"
#import "ZJAppUpdateAlertView.h"
#import "LPChooseReportTypeViewController.h"
#import "ZJIntroductionView.h"
#import "OnlineOrganizationalLifeModel.h"
#import "OnlineOLDetailViewController.h"
#import "AppUpdateViewController.h"
#import "MyBranchViewController.h"
/// 极光推送
// 引 JPush功能所需头 件
#import "JPUSHService.h"
// iOS10注册APNs所需头 件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使 idfa功能所需要引 的头 件(可选)
#import <AdSupport/AdSupport.h>

//微吼
#define VHALL_APPKEY @"38f55bd220adbb58daa5665301a2dd65"
#define VHALL_APPSECRETKEY @"594579bdd8edae29b052094cdf0f9ed9"
//极光推送
//#define PUSHID @"a14d9d633c51b0c7ee320a36"
#define PUSHID @"ed7651cb35150d629954342f" //红色版
///腾讯地图
//#define TXMap_KEY @"W2YBZ-UZLC4-6KDUF-DVCKK-YXW76-3LBND"
#define TXMap_KEY @"DMJBZ-BXCCF-7DGJY-JQSHI-RXM5K-PZBBL" 
#import "LPLeftViewController.h"
#import "XLSlideMenu.h"
#import <IQKeyboardManager.h>
//友盟统计
#import <UMMobClick/MobClick.h>
#define UMMobClick_Key  @"5982de5e07fe655f53001f90"
//友盟分享
#define  USHARE_DEMO_APPKEY @"5982de5e07fe655f53001f90"
@interface AppDelegate ()<JPUSHRegisterDelegate,AppUpdateViewControllerDelegate>

/** 引导页gif */
//@property (nonatomic, strong) ZJIntroductionView *introductionView;
/**  网络状态监听  */
@property (strong, nonatomic) Reachability  *conn;

@property (nonatomic , strong) UINavigationController * mainNav;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    application.statusBarHidden = YES;
    [NSThread sleepForTimeInterval:0.5];//设置启动页面时间
    application.statusBarHidden = NO;
  
    [self monitorNet];
//    [self netWorking_appUpdate];
    [self initTenXunMap];
    [self initPolyvSettings];
    [self initUMSocial];
    [self initUMSocialStatistics];
    [self initVHallApi];
    [self initJPushWithOptions:launchOptions];
    [self IQKeyboardManager];
    
    
    // 播放器即将播放通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoStarted:) name:@"UIMoviePlayerControllerDidEnterFullscreenNotification" object:nil];
    // 播放器即将退出通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoFinished:) name:@"UIMoviePlayerControllerDidExitFullscreenNotification" object:nil];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    AppUpdateViewController *vc = [AppUpdateViewController new];
    UINavigationController * mainNav = [[UINavigationController alloc]initWithRootViewController:vc];
    mainNav.navigationBar.hidden = YES;
    vc.delegate = self;
    self.window.rootViewController = mainNav;
    [self.window makeKeyAndVisible];
    /**  修改状态栏字体颜色  */
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    return YES;
}


#pragma mark - AppUpdateViewControllerDelegate(检测App更新) 协议方法
- (void)AppUpdateViewControllerDeleGate_show{
    
    [self changeWindowRootController];
}
- (void)changeWindowRootController{
    UINavigationController * mainNav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    
    NSMutableArray *controllers = [NSMutableArray arrayWithArray:mainNav.viewControllers];
    UIViewController *rootViewController;
    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"]) {
        rootViewController = [LoginViewController new];
        controllers[0] =rootViewController;
        [mainNav setViewControllers:controllers];
        mainNav.navigationBar.hidden = YES;
        self.window.rootViewController = mainNav;
        [self.window makeKeyAndVisible];
    }else{
        /**  自动登录  */
        [self atuoLogin];
        /**  主控制器  */
//        ZJTabBarController *zj = [[ZJTabBarController alloc] init];
//
//        //左侧菜单
//        LPLeftViewController *leftVC = [[LPLeftViewController alloc] init];
//        //创建滑动菜单
//        XLSlideMenu *slideMenu = [[XLSlideMenu alloc] initWithRootViewController:zj];
//        //设置左右菜单
//        slideMenu.leftViewController = leftVC;
        MyBranchViewController *vc = [MyBranchViewController new];
        //设置根导航控制器
        controllers[0] =vc;
        [mainNav setViewControllers:controllers];
        mainNav.navigationBar.hidden = YES;
        self.window.rootViewController = mainNav;
        [self.window makeKeyAndVisible];
    }
    
//    //引导页gif展示
//    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"yindao"]) {
//        [self.introductionView showOnViewController:rootViewController];
//    }
}

#pragma mark - 监听网络状态
- (void)monitorNet{
    
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络

                 [YJProgressHUD showMessage:@"未知网络" inView:[UIApplication sharedApplication].keyWindow afterDelayTime:2];
                break;
                
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                [YJProgressHUD showMessage:@"没有网络，请打开wifi或开启移动数据" inView:[UIApplication sharedApplication].keyWindow afterDelayTime:2];
                
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                 [YJProgressHUD showMessage:@"当前处于移动数据模式" inView:[UIApplication sharedApplication].keyWindow afterDelayTime:2];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
            
                [YJProgressHUD showMessage:@"当前处于wifi模式" inView:[UIApplication sharedApplication].keyWindow afterDelayTime:2];
                
                
                break;
        }
    }];
    [mgr startMonitoring];
    

}



#pragma mark - 自动登录获取最新信息

- (void)atuoLogin{
    if ([CManager zj_validateMobile: ZJUSERINFORMODEL.ORG_ACCOUNT.MOBILE]) {
        NSDictionary *dict = @{@"MOBILE":ZJUSERINFORMODEL.ORG_ACCOUNT.MOBILE,@"CODE_SOURCE":@"login"};
        //获取验证码
        __weak typeof(self) weakSelf = self;
        [NetWorkingManager postWithUrlString:[NetWorkingURL getMobileCode] Parameter:dict Success:^(id object) {
            NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
            if ([model.STATE isEqualToString:@"30000"]) {
                [weakSelf loginInfoCode:[object objectForKey:@"CODE"]];
            }
        } Fail:^(id object) {
           
        }];
    }
}


- (void)loginInfoCode:(NSString *)code{
    NSDictionary *dict = @{@"MOBILE":ZJUSERINFORMODEL.ORG_ACCOUNT.MOBILE,@"CODE_SOURCE":@"login",@"MOBILE_CODE":code};
    __weak typeof(self) weakSelf = self;
    [NetWorkingManager postWithUrlString:[NetWorkingURL login] Parameter:dict Success:^(id object) {
        [weakSelf judgeLoginSuccessWith:object];
    } Fail:^(id object) {
       
    }];

}
/** 判断是否登录成功 */
- (void)judgeLoginSuccessWith:(NSDictionary *)object{
    NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
    if ([model.STATE isEqualToString:@"30000"]) {//登录成功
        [[NSUserDefaults standardUserDefaults] setObject:[object yy_modelToJSONString] forKey:USER_INFO];
        [ZJUserInfoModel updateUserInfoFormNSUserDefaults];
        if (ZJUSERINFORMODEL.DEPT.count == 0 || !ZJUSERINFORMODEL.CURRENT_DEPT_MODEL.ID) {
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"isLogin"];
            [YJProgressHUD showSuccess:@"组织信息不完整" inview:[UIApplication sharedApplication].keyWindow];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[LoginViewController new]];
                self.window.rootViewController = nav;
            });
            
        }else{
            [self loginJudge];
        }
        
    }
}


- (void)loginJudge{
    NSString *string =  [ZJLoginJudgeManager loginJudge];
    //跳转页面准备数据
    ZJUserRegisterInfoModel *model = [ZJUserRegisterInfoModel new];
    model.ACCOUNT_ID = ZJUSERINFORMODEL.ORG_ACCOUNT.ID ? ZJUSERINFORMODEL.ORG_ACCOUNT.ID : @"";
    model.MOBILE = ZJUSERINFORMODEL.ORG_ACCOUNT.MOBILE ? ZJUSERINFORMODEL.ORG_ACCOUNT.MOBILE : @"";
    model.USER_ID = ZJUSERINFORMODEL.CURRENT_USER_MODEL.ID ? ZJUSERINFORMODEL.CURRENT_USER_MODEL.ID : @"";
    model.PARTYMEMBER_NAME = ZJUSERINFORMODEL.ORG_ACCOUNT.USER_NAME ? ZJUSERINFORMODEL.ORG_ACCOUNT.USER_NAME :@"";
    
    if ([string isEqualToString:@"pass"]) {//直接登录
        

    }else if ([string isEqualToString:@"check"]){//跳党员报到
        [LPCostomPressentAnimationSimilarityPushAnimation enterNextVc];
        ZJReportViewController *vc = [ZJReportViewController new];
        vc.registerModel = model;
        vc.isModel  = YES;
        ZJNavigationController *nav = [[ZJNavigationController alloc] initWithRootViewController:vc];
        [[self topViewController] presentViewController:nav animated:NO completion:nil];
        
    }else if([string isEqualToString:@"checkTwo"]){//需要 中间页面（组织报到、党员报到）
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"isLogin"];
        /**  这是该手机号未注册，自动注册 ，并且跳转选择报到页面 */
        UINavigationController *nav1 = [[UINavigationController alloc] initWithRootViewController:[LoginViewController new]];
        self.window.rootViewController = nav1;
        LPChooseReportTypeViewController *vc = [LPChooseReportTypeViewController new];
        vc.registerModel = model;
        [nav1 pushViewController:vc animated:YES];
        
    }else if([string isEqualToString:@"login"]){//跳登录页面
        [YJProgressHUD showMessage:@"请重新登录" inView:[UIApplication sharedApplication].keyWindow afterDelayTime:2.f];
        __weak typeof(self) weakSelf = self;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[LoginViewController new]];
            weakSelf.window.rootViewController = nav;
        });
    }else{
        [YJProgressHUD showMessage:@"请重新登录" inView:[UIApplication sharedApplication].keyWindow afterDelayTime:2.f];
        __weak typeof(self) weakSelf = self;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[LoginViewController new]];
            weakSelf.window.rootViewController = nav;
        });
    }
}


#pragma mark - 腾讯地图
///腾讯地图
- (void)initTenXunMap{
    QAppKeyCheck *keyCheck = [[QAppKeyCheck alloc] init];
    [keyCheck start:TXMap_KEY withDelegate:self];

}
// 这是QAppKeyCheckDelegate提供的key验证回调，用于检查传入的key值是否合法
- (void) notifyAppKeyCheckResult:(QErrorCode)errCode
{
    if (errCode == QErrorNone) {
        NSLog(@"验证成功");
    }
}
#pragma mark - 键盘控制
- (void)IQKeyboardManager{
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.enableAutoToolbar = NO;
}

#pragma mark - 友盟分享初始化
- (void)initUMSocial{
    /* 打开调试日志 */
    [[UMSocialManager defaultManager] openLog:YES];
    
    /* 设置友盟appkey */
    [[UMSocialManager defaultManager] setUmSocialAppkey:USHARE_DEMO_APPKEY];
    
    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wxf9c91a94f61155c0" appSecret:@"74557387bd6f11e7e851880bed3ece39" redirectURL:@"http://mobile.umeng.com/social"];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatTimeLine appKey:@"wxf9c91a94f61155c0" appSecret:@"74557387bd6f11e7e851880bed3ece39" redirectURL:@"http://mobile.umeng.com/social"];
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"1106078389" appSecret:@"HCyx25cfXfYeLTKt" redirectURL:@"http://mobile.umeng.com/social"];
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Qzone appKey:@"1106078389" appSecret:@"HCyx25cfXfYeLTKt" redirectURL:@"http://mobile.umeng.com/social"];
    
}

// 支持所有iOS系统
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    #pragma mark - 支付宝
    //如果极简开发包不可用，会跳转支付宝钱包进行支付，需要将支付宝钱包的支付结果回传给开发包
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            //【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
            NSLog(@"result = %@",resultDic);
        }];
        return YES;
    }
    if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回authCode
        
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            //【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
            NSLog(@"result = %@",resultDic);
        }];
        return YES;
    }
    
    #pragma mark - 友盟分享
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}



// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }
    return YES;
}

#pragma mark - 友盟统计
- (void)initUMSocialStatistics{
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
    [MobClick setLogEnabled:YES];
    UMConfigInstance.appKey = UMMobClick_Key;
    UMConfigInstance.channelId = @"";
    UMConfigInstance.ePolicy = REALTIME;
    [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK！
    
}

#pragma mark - 保利威视（视频）
- (void)initPolyvSettings{
    
    // 配置下载目录
    [PolyvSettings.sharedInstance setDownloadDir:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/plvideo/a"]];
    // 配置日志等级
    [PolyvSettings.sharedInstance setLogLevel:PLVLogLevelAll];
    // 开启 HttpDNS 功能
    [PolyvSettings.sharedInstance setHttpDNSEnable:YES];
    
    // 配置sdk加密串
    // NSString *appKey = @"你的SDK加密串";
    NSString *appKey = @"Cq5RRhkjoK5IhucEAlCcq2xKA7yIguTAg2g0LRXWdnEcp5hTYrsKFrls8XsFMoKsnYzRcu4292JjLVw7AIFyOdlkiN9sa6lCFECxdHHrv58TmRJvgOF7PDYXUq03WNyxeVQWCrsk3WMTwFUSWSFJNA==";
    // 使用默认加密秘钥和加密向量解密 SDK加密串
    NSArray *config = [PolyvUtil decryptUserConfig:[appKey dataUsingEncoding:NSUTF8StringEncoding] key:@"VXtlHmwfS2oYm0CZ" iv:@"2u9gDPKdX6GyQJKU"];
    
    [[PolyvSettings sharedInstance] initVideoSettings:[config objectAtIndex:1] Readtoken:[config objectAtIndex:2] Writetoken:[config objectAtIndex:3] UserId:[config objectAtIndex:0]];
    
    // 配置sdk加密串示例(使用网络接口)
    
}


#pragma mark - 微吼（直播）
- (void)initVHallApi{
    [VHallApi registerApp:VHALL_APPKEY SecretKey:VHALL_APPSECRETKEY];
}


#pragma mark - 极光推送
- (void)initJPushWithOptions:(NSDictionary *)launchOptions{
    // Required
    // notice: 3.0.0及以后版本注册可以这样写,也可以继续 旧的注册 式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加 定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    
    //    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:PUSHID
                          channel:@""
                 apsForProduction:NO];
    
    
    ;
    
    //接受自定义消息
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidSetup:)
                          name:kJPFNetworkDidSetupNotification
                        object:nil];
}

/**
 自定义消息
 
 @param notification 通知
 */
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];

//    NSString *content = [userInfo valueForKey:@"content"];
    //附加属性
    NSDictionary *extras = [userInfo valueForKey:@"extras"];
    
    [[ZJPushInfoManager sharedPushInfo] addPushMessage:extras];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"YBReceiveNotification" object:nil];
}
- (void)networkDidSetup:(NSNotification *)notification
{
    
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // 取得 APNs 标准信息内容
//    NSDictionary *aps = [userInfo valueForKey:@"aps"];
//    NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
//    NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge数量
//    NSString *sound = [aps valueForKey:@"sound"]; //播放的声音
    
    // 取得Extras字段内容
//    NSString *customizeField1 = [userInfo valueForKey:@"customizeExtras"]; //服务端中Extras字段，key是自己定义的

    // iOS 10 以下 Required
    [JPUSHService handleRemoteNotification:userInfo];
}

//iOS 7 Remote Notification
- (void)application:(UIApplication *)application didReceiveRemoteNotification:  (NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    NSLog(@"this is iOS7 Remote Notification");
    
    // iOS 10 以下 Required
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark- JPUSHRegisterDelegate // 2.1.9版新增JPUSHRegisterDelegate,需实现以下两个方法

// iOS 10 Support //在前台的时候收到通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center  willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    
    NSDictionary * userInfo = notification.request.content.userInfo;
//     [[NSNotificationCenter defaultCenter] postNotificationName:@"notification" object:nil userInfo:userInfo];
    [[ZJPushInfoManager sharedPushInfo] addPushMessage:userInfo];
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    else {
        // 本地通知
    }
    ZJPushInfoModel *model  =  [ZJPushInfoModel yy_modelWithJSON:userInfo];
    //改变阅读状态
    model.state = @"0";
    [[ZJPushInfoManager sharedPushInfo] addPushMessage:[model yy_modelToJSONObject]];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"YBReceiveNotification" object:nil];
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}

// iOS 10 Support //在后台运行  点击通知进入app
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler: (void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"notification" object:nil userInfo:userInfo];
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }else {
        // 本地通知
    }
    [[ZJPushInfoManager sharedPushInfo] addPushMessage:userInfo];
    
    [UIApplication sharedApplication].applicationIconBadgeNumber -=  1;
    [JPUSHService setBadge:[UIApplication sharedApplication].applicationIconBadgeNumber];
    [self PushMessage:userInfo];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"YBReceiveNotification" object:nil];
    completionHandler();  // 系统要求执行这个方法
}
//推送消息处理
- (void)PushMessage:(NSDictionary *)message{
    ZJPushInfoModel *model  =  [ZJPushInfoModel yy_modelWithJSON:message];
    //改变阅读状态
    model.state = @"1";
    [[ZJPushInfoManager sharedPushInfo] addPushMessage:[model yy_modelToJSONObject]];
    /**  0、链接 1、学习  2、活动  3、直播 4、新闻 5、需求  6、资源 */
    NSString *ID = @"";
    if ([model.dataDict.allKeys containsObject:@"id"]) {
        ID = [model.dataDict objectForKey:@"id"];
        
    }
    else{
        ID = [model.dataDict objectForKey:@"ID"];
    }
    if ([model.type isEqualToString:@"0"] && ID) {//链接
        ZJWebViewController *vc = [ZJWebViewController new];
        vc.urlString = [model.dataDict objectForKey:@"url"];
        [[ToolClass getMainNavigationController] pushViewController:vc animated:YES];
    }else if ([model.type isEqualToString:@"2"] && ID) {//活动
        NSString *big_class = [model.dataDict objectForKey:@"BIG_CLASS"];
        NSString *ONLINE = [model.dataDict objectForKey:@"ONLINE"];
        if ([big_class isEqualToString:@"1"] && [ONLINE isEqualToString:@"1"]) {
            OnlineOLDetailViewController *vc = [OnlineOLDetailViewController new];
            OnlineOrganizationalLifeModel *online = [OnlineOrganizationalLifeModel new];
            online.ID = ID;
            online.NAME = model.title;
            vc.model = online;
           
            vc.block = ^{
                [[ZJPushInfoManager sharedPushInfo] removePushMessageWithID:model.ID];
            };

            [[ToolClass getMainNavigationController] pushViewController:vc animated:YES];
        }else{
            LPActivityDetailViewController *vc = [LPActivityDetailViewController new];
            ActivityJoinDetailModel *model1= [ActivityJoinDetailModel new];
            model1.ID = ID;
            model1.NAME = model.title;
            vc.model = model1;
            vc.actBlock = ^() {
                [[ZJPushInfoManager sharedPushInfo] removePushMessageWithID:model.ID];
            };
           
            [[ToolClass getMainNavigationController] pushViewController:vc animated:YES];
        }
    }else if ([model.type isEqualToString:@"5"] && ID) {//需求
        ZJShareClaimViewController *vc = [ZJShareClaimViewController new];
        ShareOpenRequestModel *model1 = [ShareOpenRequestModel new];
        vc.noDataBlock = ^(NSString *ID) {
            [[ZJPushInfoManager sharedPushInfo] removePushMessageWithID:ID];
        };
        model1.ID = ID;
        vc.model = model1;
      
        [[ToolClass getMainNavigationController] pushViewController:vc animated:YES];
    }else if ([model.type isEqualToString:@"6"] && ID) {//资源
        /**  资源类型判断是预约资源还是发布资源  */
        NSString *type = [model.dataDict objectForKey:@"type"];
         /**  type:1资源,2预约  */
        if ([type isEqualToString:@"1"]) {
            ShareResouceDetailViewController *vc = [ShareResouceDetailViewController new];
            vc.ID = ID;
            vc.type = [model.dataDict objectForKey:@"r_type"];
            vc.block  = ^() {
                [[ZJPushInfoManager sharedPushInfo] removePushMessageWithID:model.ID];
            };
            [[ToolClass getMainNavigationController] pushViewController:vc animated:YES];
        }else{
            
            
            GTResouseDetailViewController *vc = [GTResouseDetailViewController new];
            vc.ID = ID;
            vc.block  = ^() {
                [[ZJPushInfoManager sharedPushInfo] removePushMessageWithID:model.ID];
            };
            [[ToolClass getMainNavigationController] pushViewController:vc animated:YES];
            
        }

    }
}

#pragma mark - 屏幕旋转
//AppDelegate.m
-  (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    
    if(_isFull){
        return UIInterfaceOrientationMaskLandscape;
    }
    return UIInterfaceOrientationMaskPortrait;
}
- (void)videoStarted:(NSNotification *)sender{

    self.isFull = YES;
}
- (void)videoFinished:(NSNotification *)sender{
    
    self.isFull = NO;
}






- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


//- (ZJIntroductionView *)introductionView{
//    if (_introductionView == nil){
//        _introductionView = [ZJIntroductionView new];
//    }
//    return _introductionView;
//}

@end
